<template>
    <div class="register-container">
      <el-card class="register-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h2>用户注册</h2>
          </div>
        </template>
  
        <el-form 
          ref="registerForm"
          :model="form"
          :rules="rules"
          label-width="120px"
          label-position="top"
          @submit.prevent="handleRegister"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="form.username"
              placeholder="请输入用户名"
              clearable
            />
          </el-form-item>
  
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码（至少6位）"
              show-password
            />
          </el-form-item>
  
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="form.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              show-password
            />
          </el-form-item>
  
          <el-form-item>
            <el-button
              type="primary"
              :loading="loading"
              native-type="submit"
              class="register-btn"
            >
              {{ loading ? '注册中...' : '立即注册' }}
            </el-button>
          </el-form-item>
        </el-form>
  
        <div class="login-link">
          已有账号？<el-link type="primary" @click="gotoLogin">去登录</el-link>
        </div>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { ElMessage } from 'element-plus';
  import { useRouter } from 'vue-router';
  import * as contract from '../../test/Truffle-ABI.js';
  import { useStore } from 'vuex';
  
  const router = useRouter();
  const registerForm = ref(null);
  const loading = ref(false);
  const web3Initialized = ref(false);
  const store = useStore()
  
  const form = reactive({
    username: '',
    password: '',
    confirmPassword: ''
  });
  
  const validateConfirmPassword = (rule, value, callback) => {
    if (value !== form.password) {
      callback(new Error('两次输入的密码不一致'));
    } else {
      callback();
    }
  };
  
  const rules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '至少 6 个字符', trigger: 'blur' }
    ],
    confirmPassword: [
      { required: true, message: '请再次输入密码', trigger: 'blur' },
      { validator: validateConfirmPassword, trigger: 'blur' }
    ]
  };
  
  onMounted(async () => {
    try {
      await contract.initWeb3();
      web3Initialized.value = true;
    } catch (error) {
      ElMessage.error(`Web3初始化失败: ${error.message}`);
    }
  });
  
  const handleRegister = async () => {
    try {
      const valid = await registerForm.value.validate();
      if (!valid) return;
      
      if (!web3Initialized.value) {
        throw new Error('区块链连接未初始化');
      }
  
      loading.value = true;
      
      const txHash = await contract.register(
        form.username,
        form.password
      );
  
      if (txHash) {
        ElMessage.success({
          message: `注册成功！正在跳转至登录界面`,
          duration: 5000
        });
        store.commit('setTxt','用户登录')
        router.push('/login');
      }
    } catch (error) {
      console.error('注册失败:', error);
      ElMessage.error({
        message: `注册失败: ${error.message || '区块链操作失败'}`,
        duration: 3000
      });
    } finally {
      loading.value = false;
    }
  };
  
  const gotoLogin = () => {
    router.push('/login');
  };
  </script>
  
  <style scoped>
  .register-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 90vh;
    padding: 20px;
    box-sizing: border-box;
  }
  
  .register-card {
    width: 480px;
    border-radius: 8px;
    margin: auto; /* 关键修改点2：双重保障居中 */
    transform: translateY(-10%); /* 可选：微调垂直位置 */
  }
  .card-header {
    text-align: center;
  }
  
  .register-btn {
    width: 100%;
    margin-top: 20px;
  }
  
  .login-link {
    text-align: center;
    margin-top: 20px;
    color: #606266;
  }
  
  .el-link {
    margin-left: 5px;
  }
  
  .login-container {
    background: url('../assets/椎名真白.png') no-repeat center center fixed;
    background-size: cover;
    position: relative;
  }
  
  .login-card {
    position: relative;
    z-index: 2; /* 确保卡片在遮罩层之上 */
  }
</style>